package com.veeder.datacollection.rs232.response.handler;

import java.util.logging.Logger;

import com.veeder.datacollection.exception.SyntaxException;
import com.veeder.datacollection.rs232.Command;
import com.veeder.datacollection.rs232.response.RS232Response;

public abstract class CmdRspParser implements RspParser{
	
	protected final Logger logger;
		
	public CmdRspParser() {
		this.logger = Logger.getLogger(this.getClass().getName());
		logger.setUseParentHandlers(true);
	}	
	
	@Override
	public RS232Response parseResponse(String rawResponse)throws SyntaxException{
		validateResponse(rawResponse);
		String coreResponse = getCoreResponse(rawResponse);	
		return parseCoreResponse(coreResponse);
	}
	
	
	public abstract RS232Response parseCoreResponse(String coreResponse) throws SyntaxException;
	
	
	public void validateResponse(String rawResponse) throws SyntaxException{
		if(rawResponse==null||rawResponse.length()<5){
			throw new SyntaxException("null response or response too short");
		}
		else if(!rawResponse.startsWith(Command.SOH)){
			throw new SyntaxException("missing "+ Command.SOH );
		}else{
			char type =rawResponse.charAt(1);
			if(type=='i'){
				if(!rawResponse.contains(Command.TAG)){
					throw new SyntaxException("missing "+ Command.TAG);
				}
			}else{
				throw new SyntaxException("unsupported response type");
			}
		}
		
	}
	
	private String getCoreResponse(String rawResponse){
		int startPoint = rawResponse.indexOf('i');
		int endPoint = rawResponse.indexOf(Command.TAG);
	   return rawResponse.substring(startPoint,endPoint);	
	}
		
}
